package com.neuedu.yyzx.config.security;

import com.neuedu.yyzx.common.Ret;
import com.neuedu.yyzx.po.Menu;
import com.neuedu.yyzx.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 金山
 * 项目：yyzx
 * site: https://blog.fulfill.com.cn
 * 描述  权限增强
 * @data 2025/4/1614:34
 */
@Aspect
@Component
@EnableAspectJAutoProxy
public class SecurityAdvice {

    @Autowired
    UserService userService;

    @Autowired
    SecurityUtils securityUtils;

    @Pointcut("execution(* com.neuedu.yyzx.controller.*Controller.*(..))")
    public void controllerMethods() {
    }


    @Around("controllerMethods()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;


        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        System.out.println("method = " + method);
        PreAuthorize annotation = null;
        String authorize = null;

        // 获取权限注解
        if (method != null) {
            annotation = method.getAnnotation(PreAuthorize.class);
        }

        // 获取权限注解中的 校验值
        if (annotation != null) {
            authorize = annotation.value();
        }

        // 判断校验权限是否通过
        if (authorize != null && !"".equals(authorize.trim())) {
            System.out.println("authorize = " + authorize);

            boolean success = validatePermission(authorize);
            System.out.println("validatePermission: success = " + success);

            // 没有需要验证的权限
            if (!success) {
                return Ret.forbidden();
            }

        }


        // 执行controller方法
        try {
            result = point.proceed(point.getArgs());
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

        return result;

    }


    /**
     * 验证用户是否拥有权限
     *
     * @param authorize
     * @return
     */
    private boolean validatePermission(String authorize) {

        List<Menu> list = userService.getUserGrantMenus(securityUtils.getUserInfo().getId());

        List<String> perms = new ArrayList<>();


        list.forEach(menu -> {
            perms.add(menu.getPerms());
        });


        return perms.indexOf(authorize) != -1;


    }


}
